# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time

  # See ActionController::RequestForgeryProtection for details
  # Uncomment the :secret if you're not using the cookie session store
  protect_from_forgery :secret => '425b74cf13c5527300b2bbb3affe0ca0'
  layout 'standard' # 所有 View 都使用 standard 樣版.
  
  
  yullio_page_width :doc2
  yullio_column_template :yui_t2
  
  
  protected 
  
  # 限制存取.
  def authorize
    if User.find_by_id((session[:user_id])) # 看有無此ID.
      user = User.find_by_id((session[:user_id]))
      if user.id != @@admin_id # 若此 ID 的使用者編號不對就跳回登入畫面.
        redirect_to_login
      end
    else
      redirect_to_login
    end
  end
  
  # 重新導向錯誤網頁.
  def redirect_to_error_page
    redirect_to "http://tangblack.googlepages.com/%E9%9B%BB%E5%A0%B1%E9%8C%AF%E8%AA%A4%E8%A8%8A%E6%81%AF"
  end
  
  # 紀錄目前的 URL .
  def record_uri
    session[:original_uri] = request.request_uri
  end
  
  # 若在 Session 中找不到便新增一個陣列來存放電報編號.
  def find_favorite
    if session[:favorite] # Session 中已經有最愛電報編號,就續用.
      @favorite = Favorite.find(session[:favorite])
    else # Session 中沒有最愛電報編號,就建立一個新的最愛電報編號.
      @favorite = Favorite.new
      @favorite.save
      session[:favorite] = @favorite.id
    end
    
    @favorite
  end
  
  # 導向原本的網頁.
  def redirect_to_original_uri
    uri = session[:original_uri]
    session[:original_uri] = nil;
    redirect_to uri
  end
  
  # 產生驗證圖片物件,並填入 Session 中.
  def put_noisy_image_into_session
    session[:noisy_image] = nil
    unless session[:noisy_image]
      session[:noisy_image] = NoisyImage.new(4)
      session[:code] = session[:noisy_image].code
    end
  end
  
  private
  
  # 管理者編號(DB).
  @@admin_id = 541702176
  
  # 重新導向登入畫面.
  def redirect_to_login
    record_uri
    flash[:notice] = '請先登入'
    redirect_to :controller => :user, :action => :login
  end
  
end
